package cn.xtcode.domain.trade.service.lock.filter;

import cn.xtcode.domain.trade.adapter.repository.ITradeRepository;
import cn.xtcode.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.xtcode.domain.trade.model.entity.TradeLockRuleCommandEntity;
import cn.xtcode.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import cn.xtcode.domain.trade.service.lock.factory.TradeRuleFilterFactory;
import cn.xtcode.types.design.framework.link.model2.handler.ILogicHandler;
import cn.xtcode.types.enums.ActivityStatusEnumVO;
import cn.xtcode.types.enums.ResponseCode;
import cn.xtcode.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author xt-code
 * @Description: 活动可用性过滤
 * @Create 2025/5/10 22:38
 */
@Slf4j
@Service
public class ActivityUsabilityRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-用户活动可用性检验 userId{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());
        GroupBuyActivityEntity groupBuyActivityEntity = repository.queryGroupBuyActivityByActivityId(requestParameter.getActivityId());

        //1.当前活动并不生效
        if(!ActivityStatusEnumVO.EFFECTIVE.equals(groupBuyActivityEntity.getStatus())){
            throw new AppException(ResponseCode.E0101);
        }

        //2.判断当前时间是否处于生效期内
        Date currentTime = new Date();
        if(currentTime.before(groupBuyActivityEntity.getStartTime()) || currentTime.after(groupBuyActivityEntity.getEndTime())){
            throw new AppException(ResponseCode.E0102);
        }

        dynamicContext.setGroupBuyActivity(groupBuyActivityEntity);

        return next(requestParameter, dynamicContext);
    }
}
